/**
 * Licensed to the Apache Software Foundation （ASF） under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * （the "License"）； you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * <p>
 * https://www.q3z3.com
 * QQ : 939313737
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.platform.modules.sms.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.platform.common.config.PlatformConfig;
import com.platform.modules.sms.enums.SmsChannelEnum;
import com.platform.modules.sms.enums.SmsTemplateEnum;
import com.platform.modules.sms.enums.SmsTypeEnum;
import com.platform.common.enums.YesOrNoEnum;
import com.platform.common.exception.BaseException;
import com.platform.common.utils.redis.RedisUtils;
import com.platform.modules.sms.service.SmsService;
import com.platform.modules.sms.vo.SmsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 * token 服务层
 */
@Service("smsService")
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Object sendSms(SmsVo smsVo) {
        // 验证手机号
        if (!Validator.isMobile(smsVo.getPhone())) {
            throw new BaseException("请输入正确的手机号");
        }
        SmsTypeEnum smsType = smsVo.getType();
        String key = smsType.getPrefix().concat(smsVo.getPhone());

        // 生成验证码
        String code = String.valueOf(RandomUtil.randomInt(1000, 9999));

        if (redisUtils.hasKey(key)){
            throw new BaseException("获取短信过于频繁，请5分钟后再获取");
        }
        // 存入缓存
        redisUtils.set(key, code, smsType.getTimeout(), TimeUnit.MINUTES);

        // 发送短信
        if (YesOrNoEnum.YES.equals(PlatformConfig.SMS)) {
            Dict dict = Dict.create()
                    .set("code", code);

//            if (smsVo.getChannel().equals(SmsChannelEnum.LTX_CODE)){
//                dict.set("corpId","JX008281");
//                dict.set("pwd","123456");
//            }else if (smsVo.getChannel().equals(SmsChannelEnum.WPJ_CODE)){
                dict.set("corpId","JX008282");
                dict.set("pwd","123456");
//            }

            try {
                doSendSms(smsVo.getPhone(), SmsTemplateEnum.VERIFY_CODE, dict);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return Dict.create().set("code", null).set("expiration", smsType.getTimeout());
        }
        return Dict.create().set("code", code).set("expiration", smsType.getTimeout());
    }

    @Override
    public void verifySms(String phone, String code, SmsTypeEnum type) {
        // 验证手机号
        if (!Validator.isMobile(phone)) {
            throw new BaseException("请输入正确的手机号");
        }
        String key = type.getPrefix().concat(phone);
        if (!redisUtils.hasKey(key)) {
            throw new BaseException("验证码已过期，请重新获取");
        }
        String value = redisUtils.get(key);
        if (value.equalsIgnoreCase(code)) {
            redisUtils.delete(key);
        } else {
            throw new BaseException("验证码不正确，请重新获取");
        }
    }

    /**
     * 执行发送短信
     *
     * @param phone
     * @param templateCode
     * @param dict
     */
    @Override
    public void doSendSms(String phone, SmsTemplateEnum templateCode, Dict dict) throws Exception {
        // 短信待集成


        String corpId = dict.getStr("corpId");//账户名
        String pwd = dict.getStr("pwd");//密码
        String send_content = "您好，您的验证码为" + dict.getStr("code") + "，验证码一分钟内有效，请勿向他人泄露。";

        String content = URLEncoder.encode(send_content, "GBK");

        System.out.println(send_content);


        URL url = new URL("https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID=" + corpId + "&Pwd=" + pwd + "&Mobile=" + phone + "&Content=" + content + "&Cell=&SendTime=");
        BufferedReader in = null;
        String inputLine = "";
        String message = "";
        try {
            System.out.println("开始发送短信手机号码为 ：" + phone);
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((inputLine = in.readLine()) != null) {
                message += inputLine;
            }

        } catch (Exception e) {
            System.out.println("网络异常,发送短信失败！");
            e.printStackTrace();
            inputLine = "err";
        }
        System.out.println("结束发送短信返回值：  " + message);
    }

}
